$().ready(function() {
	validateRule();
	$("#tal").hide();	
});

$.validator.setDefaults({
	submitHandler : function() {
		save();
	}
});


$("#purpose").change(function(){
	  var purpose=$(this).val();
	  if(purpose=="2"){

		  $("#shopsDiv1").show();
		  $("#shopsDiv2").show();
		  $("#foundationMatchingDiv2").show();
		  
		  $("#foundationMatchingDiv1").hide();
		  $("#accommodationStationDiv").hide();
		  $("#officeTypeDiv").hide();
		  $("#officeBuildingManagementIdDiv").hide();
		  $("#officeNameDiv").hide();
		  $("#officeLocalDiv").hide();
		  $("#floorDiv").hide();
	  }else{
		  $("#shopsDiv1").hide();
		  $("#shopsDiv2").hide();
		  $("#foundationMatchingDiv2").hide();
		  
		  $("#foundationMatchingDiv1").show();
		  $("#accommodationStationDiv").show();
		  $("#officeTypeDiv").show();
		  $("#officeBuildingManagementIdDiv").show();
		  $("#officeNameDiv").show();
		  $("#officeLocalDiv").show();
		  $("#floorDiv").show();
	  }
});


$("input[name=officeProperty]").click(function(){
	var  officeProperty =  $("input[name='officeProperty']:checked").val()	
	if(officeProperty=="0"){
		$("#rentMethodDiv").show();
		$("#leaseTermDiv").show();
		$("#lrentFreeDiv").show();
		$("#depositDiv").show();
		$("#tal").hide();
	}
	if(officeProperty=="1"){
		$("#rentMethodDiv").hide();
		$("#leaseTermDiv").hide();
		$("#depositDiv").hide();
		$("#tal").show();
	}
});



$("#metro").change(function(){
	  var metro=$(this).val();
	  if(metro=="0"){
		  $("#metroKil").attr("readonly","readonly")
		  $("#metroKil").val("");
	  }else{
		  $("#metroKil").removeAttr("readonly")
	  }
});


$("input[name=propertyFeeFlg]").click(function(){
	var  propertyFeeFlg =  $("input[name='propertyFeeFlg']:checked").val()	
	if(propertyFeeFlg=="2"){
		$("#propertyFeeDiv").show();
	}
	if(propertyFeeFlg=="1"){
		$("#propertyFeeDiv").hide();
	}
});


var $button = $('#upload'),
//选择文件按钮
$file = $("#files"),
//回显的列表
$list = $('.file-list'),
//选择要上传的所有文件
fileList = [];
//当前选择上传的文件
var curFile;
// 选择按钮change事件，实例化fileReader,调它的readAsDataURL并把原生File对象传给它，
// 监听它的onload事件，load完读取的结果就在它的result属性里了。它是一个base64格式的，可直接赋值给一个img的src.
$file.on('change', function (e) {
//上传过图片后再次上传时限值数量
var numold = $('li').length;
if(numold >= 10){
    layer.alert('最多上传10张图片');
    return;
}
//限制单次批量上传的数量
var num = e.target.files.length;
var numall = numold + num;
if(num >10 ){
   layer.alert('最多上传10张图片');
   return;
}else if(numall > 10){
    layer.alert('最多上传10张图片');
    return;
}
//原生的文件对象，相当于$file.get(0).files;//files[0]为第一张图片的信息;
curFile = this.files;
//curFile = $file.get(0).files;
//console.log(curFile);
//将FileList对象变成数组
fileList = fileList.concat(Array.from(curFile));
//console.log(fileList);
for (var i = 0, len = curFile.length; i < len; i++) {
    reviewFile(curFile[i])
}
$('.file-list').fadeIn(100);
})


function reviewFile(file) {
//实例化fileReader,
var fd = new FileReader();
//获取当前选择文件的类型
var fileType = file.type;
//调它的readAsDataURL并把原生File对象传给它，
fd.readAsDataURL(file);//base64
//监听它的onload事件，load完读取的结果就在它的result属性里了
	fd.onload = function () {
		if (/^image\/[jpeg|png|jpg|gif|jpg]/.test(fileType)) {
		
			$list.append('<li id = "img" style="border:solid red px; margin:5px 5px;" class="file-item"><img src="' + this.result + '" alt="" height="150"><span class="file-del">删除 </span><span class="file-radio"class="">选中 <input  type="radio" id="status" name="status" onclick="' + this.result + '" value=="' + this.result + '"  /></span></li>').children(':last').hide().fadeIn(100);
	
		} else {
			$list.append('<li id = "D99" class="file-item"><span class="file-name">' + file.name + '</span><span  id = "D99" class="file-del">删除</span></li>')
			layer.msg("请您选择有效的图片格式！");

		}

	}
}

//点击选中事件：
$(".file-list").on('click', '.file-radio', function (id) {
	let $parent = $(this).parent()
	console.log($parent);
	let index = $parent.index();
	$('#indexradio').val(index);
});

//点击删除按钮事件：
$(".file-list").on('click', '.file-del', function () {
	let $parent = $(this).parent()
	console.log($parent);
	let index = $parent.index();

	fileList.splice(index, 1);
	$parent.fadeOut(100, function () {
		$parent.remove()
	});
});


function save() {
	
	 var formData = new FormData();
	    for (var i = 0, len = fileList.length; i < len; i++) {
	        //console.log(fileList[i]);
	        formData.append('files', fileList[i]);
	    }
	    
	  var  officeProperty =  $("input[name='officeProperty']:checked").val()
	  formData.append('officeProperty', officeProperty);
	  
	  	//判断出租出售
		 if(officeProperty=='0'){//出租
			 
		  var rentMethod=$("#rentMethod").find("option:selected").val();
		  formData.append('rentMethod', rentMethod);
		  
		  //起租期
		  var leaseTerm=$("#leaseTerm").val();
		  formData.append('leaseTerm', leaseTerm);
		  //免租期
		  var rentFree=$("#rentFree").val();
		  formData.append('rentFree', rentFree);
			 
		 }else{//出售
			 
			  formData.append('rentMethod', '2');			 
		 }
	  //文件索引
	  var indexradio=$("#indexradio").val();
	  formData.append('indexradio', indexradio);   
	  //类型
	  var purpose=$("#purpose").find("option:selected").val();
	  formData.append('purpose', purpose);
	  
	  //商铺
	  if(purpose == '2'){
		  // 形态
		  var hform=$("#hform").find("option:selected").val();
		  formData.append('hform', hform);
		  // 行业
		  var industry=$("#industry").find("option:selected").val();
		  formData.append('industry', industry);
		  // 附属设施
		  //var facilities=$("#facilities").find("option:selected").val();
		  //formData.append('facilities', facilities);
		  // 临街情况
		  var streetCondition=$("#streetCondition").find("option:selected").val();
		  formData.append('streetCondition', streetCondition);
		  //楼层情况
		  var floorCondition=$("#floorCondition").find("option:selected").val();
		  formData.append('floorCondition', floorCondition);
		  // 经营状况
		  var managementCondition=$("#managementCondition").find("option:selected").val();
		  formData.append('managementCondition', managementCondition);	 
		  //性质
		  var officeSituation=$("#officeSituation").find("option:selected").val();
		  formData.append('officeSituation', officeSituation);
		  //可注册
		  var  registered =  $("input[name='registered']:checked").val()
		  formData.append('registered', registered);
		  //区域
		  var area=$("#area").find("option:selected").val();
		  formData.append('area', area);
		  //地铁线
		  var metro=$("#metro").find("option:selected").val();
		  formData.append('metro', metro);
		  //距离地铁站公里
		  var metroKil=$("#metroKil").val();
		  formData.append('metroKil', metroKil);
		  //楼名称
		  var officeName=$("#officeName").val();
		  formData.append('officeName', officeName);
		  //楼地址
		  var officeLocal=$("#officeLocal").val();
		  formData.append('officeLocal', officeLocal);
		  //装修
		  var renovation=$("#renovation").find("option:selected").val();
		  formData.append('renovation', renovation);
		  //可分割
		  var  separable =  $("input[name='separable']:checked").val()
		  formData.append('separable', separable);
		  //楼层
		  var floor=$("#floor").val();
		  formData.append('floor', floor);
		  //第几层
		  var buildingNumber=$("#buildingNumber").val();
		  formData.append('buildingNumber', buildingNumber);
		  //共几楼
		  var floorAll=$("#floorAll").val();
		  formData.append('floorAll', floorAll);
		  //建筑面积
		  var builtArea=$("#builtArea").val();
		  formData.append('builtArea', builtArea);
		  //得房率
		  var roomRate=$("#roomRate").val();
		  formData.append('roomRate', roomRate);
		  //配套
		  var foundationMatching = "";
		  $("input[name='foundationMatching2']:checked").each(function (index, item) {
		        
		        if ($("input[name='foundationMatching2']:checked").length-1==index) {
		        	foundationMatching += $(this).val();
		        } else {
		        	foundationMatching += $(this).val() + ",";
		        }  
		  });
		  formData.append('foundationMatching', foundationMatching);
		  //描述
		  var peripheralMatching=$("#peripheralMatching").val();
		  formData.append('peripheralMatching', peripheralMatching);
		  //金额
		  var money=$("#money").val();
		  formData.append('money', money);
		  //是否含物业费
		  var  propertyFeeFlg =  $("input[name='propertyFeeFlg']:checked").val()
		  formData.append('propertyFeeFlg', propertyFeeFlg);
		  //支付方式
		  var deposit=$("#deposit").find("option:selected").val();
		  formData.append('deposit', deposit);
		  //标题
		  var title=$("#title").val();
		  formData.append('title', title);
		  //用户编号
		  var userId=$("#userId").val();
		  formData.append('userId', userId);
	   } 
	  
	 //写字楼
	 if(purpose == '1'){  
		  //类别
		  var officeType=$("#officeType").find("option:selected").val();
		  formData.append('officeType', officeType);
		  //性质
		  var officeSituation=$("#officeSituation").find("option:selected").val();
		  formData.append('officeSituation', officeSituation);
		  //可注册
		  var  registered =  $("input[name='registered']:checked").val()
		  formData.append('registered', registered);
		  //区域
		  var area=$("#area").find("option:selected").val();
		  formData.append('area', area);
		  //经典写字楼
		  var officeBuildingManagementId=$("#officeBuildingManagementId").find("option:selected").val();
		  formData.append('officeBuildingManagementId', officeBuildingManagementId);
		  //地铁线
		  var metro=$("#metro").find("option:selected").val();
		  formData.append('metro', metro);
		  //距离地铁站公里
		  var metroKil=$("#metroKil").val();
		  formData.append('metroKil', metroKil);
		  //楼名称
		  var officeName=$("#officeName").val();
		  formData.append('officeName', officeName);
		  //楼地址
		  var officeLocal=$("#officeLocal").val();
		  formData.append('officeLocal', officeLocal);
		  //装修
		  var renovation=$("#renovation").find("option:selected").val();
		  formData.append('renovation', renovation);
		  //可分割
		  var  separable =  $("input[name='separable']:checked").val()
		  formData.append('separable', separable);
		  //楼层
		  var floor=$("#floor").val();
		  formData.append('floor', floor);
		  //第几层
		  var buildingNumber=$("#buildingNumber").val();
		  formData.append('buildingNumber', buildingNumber);
		  //共几楼
		  var floorAll=$("#floorAll").val();
		  formData.append('floorAll', floorAll);
		  //建筑面积
		  var builtArea=$("#builtArea").val();
		  formData.append('builtArea', builtArea);
		  //得房率
		  var roomRate=$("#roomRate").val();
		  formData.append('roomRate', roomRate);
		  //配套
		  var foundationMatching = "";
		  $("input[name='foundationMatching1']:checked").each(function (index, item) {
		        
		        if ($("input[name='foundationMatching1']:checked").length-1==index) {
		        	foundationMatching += $(this).val();
		        } else {
		        	foundationMatching += $(this).val() + ",";
		        }  
		  });
		  formData.append('foundationMatching', foundationMatching);
		  //描述
		  var peripheralMatching=$("#peripheralMatching").val();
		  formData.append('peripheralMatching', peripheralMatching);
		  //金额
		  var money=$("#money").val();
		  formData.append('money', money);
		  //是否含物业费
		  var  propertyFeeFlg =  $("input[name='propertyFeeFlg']:checked").val()
		  formData.append('propertyFeeFlg', propertyFeeFlg);
		  //可容纳工位
		  var accommodationStation=$("#accommodationStation").val();
		  formData.append('accommodationStation', accommodationStation);
		  //支付方式
		  var deposit=$("#deposit").find("option:selected").val();
		  formData.append('deposit', deposit);
		  //标题
		  var title=$("#title").val();
		  formData.append('title', title);
		  //用户编号
		  var userId=$("#userId").val();
		  formData.append('userId', userId);
	  }	  	  
	 
	  if(propertyFeeFlg!="1"){	  
		  var  propertyFee = $("#propertyFee").val();
		  formData.append('propertyFee', propertyFee);
	  }else{
		  formData.append('propertyFee', 0.00);
	  }
	 	  	  
	  var telname=$("#telname").val();
	  formData.append('telname', telname);
	  
	  var tel=$("#tel").val();
	  formData.append('tel', tel);	  
	  
	    $.ajax({
	        url: '/xzl/housesInfo/save',
	        type: 'post',
	        data: formData,
	        processData: false,
	        contentType: false,
	        success: function (data) {
	        	layer.msg("操作成功");
	        	document.getElementById("signupForm").reset();
	        	$("li").remove();
	        	fileList = []
	            parent.reLoad();
	            var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
	            parent.layer.close(index);
	        }
	    })
}


//手机号码验证身份证正则合并：(^\d{15}$)|(^\d{17}([0-9]|X)$)
jQuery.validator.addMethod("isPhone",function(value,element){
	var length = value.length;
	var phone=/^1[3|4|5|7|8][0-9]\d{8}$/;
	return this.optional(element)||(length == 11 && phone.test(value));
},"请填写正确的11位手机号");


function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			officeName : {
				required : true,
				maxlength:100
			},
			officeLocal : {
				required : true,
				maxlength:200
			},
			floor : {
				required : true,
				maxlength:10,
				number: true
			},
			buildingNumber : {
				required : true,
				maxlength:5
			},
			builtArea : {
				required : true,
				maxlength:11,
				number: true
			},
			roomRate : {
				required : true,
				maxlength:11,
				number: true
			},
			money : {
				required : true,
				maxlength:11,
				number: true
			},
			leaseTerm : {
				required : true,
				maxlength:11,
				number: true
			},
			rentFree : {
				required : true,
				maxlength:11,
				number: true
			},
			deposit : {
				required : true,
				maxlength:11
			},
			payment : {
				required : true,
				maxlength:11
			},
			title : {
				required : true,
				maxlength:64
			},
			describes : {
				required : true,
				maxlength:500
			},
			telname : {
				required : true,
				maxlength:20
			},
			tel : {
				required : true,
				maxlength:20,
				isPhone: true
			},
			accommodationStation:{
				required : true,
				maxlength:30
			},
			floorAll:{
				required : true,
				maxlength:10,
				number: true
			},
			metroKil:{
				maxlength:11,
				number: true
			},
			peripheralMatching:{
				maxlength:200
			}
		},
		messages : {
			name : {
				required : icon + "请输入姓名"
			}
		}
	})
}